#include "stdafx.h"
#include "CollisionManager.h"
#include "IHittable.h"

// Utilities
#include "Log.h"
#include "Object.h"

using namespace std;

void CollisionManager::clear()
{
	for (HITTABLE_MAP::iterator iter = HittableMap.begin();
		iter != HittableMap.end();
		++iter)
	{
		delete iter->second;
	}
	HittableMap.clear();

	FactoryManager<IHittableFactory>::clear();
}

CollisionManager::~CollisionManager( void )
{
	clear();
}

CollisionManager::CollisionManager( void )
{

}

bool CollisionManager::on_collision( Object& o1, Object& o2 )
{
	string sig(o1.signature());
	sig += o2.signature();

	FACTORY_MAP::iterator Factory = FactoryMap.find(sig);
	if (Factory == FactoryMap.end())
	{
		// No such factory registered.
		return false;
	}
	HITTABLE_MAP::iterator Interface = HittableMap.find(Factory->second);
	if (Interface == HittableMap.end())
	{
		IHittable* hittable = Factory->second->create_instance();
		pair<HITTABLE_MAP::iterator, bool> ret = HittableMap.insert(
			make_pair(Factory->second, hittable)
		);
		if (!ret.second)
		{
			// Insertion failed.
			return false;
		}
		Interface = ret.first;
	}
	return Interface->second->hit(o1, o2);
}


